package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

//gin引擎
var engine *gin.Engine

//
var LOC, _ = time.LoadLocation("Asia/Shanghai")

func main() {

	if initCfg() {

		fmt.Println("start server")
		gin.SetMode(gin.ReleaseMode)
		engine = gin.New()
		//使用日志
		engine.Use(gin.Logger())
		//使用Panic处理方案
		engine.Use(gin.Recovery())

		engine.GET("/", index)

		engine.GET("/lxtime", lxtime)

		engine.GET("/shutdown", shutdown)

		engine.GET("/reboot", reboot)

		engine.POST("/settime", settime)

		engine.Run(fmt.Sprintf("%s:%s", ServerCfg.SvrCfg.ListenAddr, ServerCfg.SvrCfg.Port))
	} else {
		fmt.Println("server conf error")
	}
}

func initCfg() bool {
	ServerCfg = NewConfig("conf.ini")
	if ServerCfg == nil {
		return false
	}
	if ServerCfg.CliCfg.LunXunTime < 1 {
		return false
	}

	return true
}

func index(ctx *gin.Context) {
	//strtm := time.Now().Format("2006-1-2 15:04:05")
	//ctx.JSON(http.StatusOK, gin.H{"code": 0, "msg": "success", "data": strtm})
	engine.LoadHTMLGlob("index.html")
	t := strings.Split(ServerCfg.CliCfg.ShutdownTime, " ")
	cfg := IndexPageObj{
		Date:   t[0],
		Time:   t[1],
		Zhouqi: ServerCfg.CliCfg.LunXunTime,
	}
	//fmt.Printf("%v\n", cfg)
	ctx.HTML(http.StatusOK, "index", cfg)
}

func lxtime(ctx *gin.Context) {
	ctx.JSON(http.StatusOK, gin.H{"code": 0, "msg": "success", "data": fmt.Sprintf("%d", ServerCfg.CliCfg.LunXunTime)})

}

func docmd(ctx *gin.Context, cmd string) {
	ntm, err := time.ParseInLocation("2006-1-2 15:04:05", time.Now().Format("2006-1-2 15:04:05"), LOC)
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{"code": 1, "msg": err.Error(), "data": ""})
		return
	}
	//转换关机时间
	stime, err := time.ParseInLocation("2006-1-2 15:04:05", ServerCfg.CliCfg.ShutdownTime, LOC)

	if err == nil && (ntm.After(stime) || ntm.Equal(stime)) {
		if ntm.Year() == stime.Year() && ntm.Month() == stime.Month() && ntm.Day() == stime.Day() {
			ctx.JSON(http.StatusOK, gin.H{"code": 0, "msg": "success", "data": cmd})
		} else {
			ctx.JSON(http.StatusOK, gin.H{"code": 0, "msg": "", "data": fmt.Sprintf("%d", ServerCfg.CliCfg.LunXunTime)})
		}
	} else {
		if err != nil {
			ctx.JSON(http.StatusOK, gin.H{"code": 1, "msg": err.Error(), "data": ""})
		} else {
			ctx.JSON(http.StatusOK, gin.H{"code": 0, "msg": "", "data": ""})
		}
	}
}

func shutdown(ctx *gin.Context) {
	docmd(ctx, "shutdown")
}

func reboot(ctx *gin.Context) {
	docmd(ctx, "reboot")
}

func settime(ctx *gin.Context) {

	b, err := ioutil.ReadAll(ctx.Request.Body)
	if err == nil {
		param := IndexPageObj{}
		err = json.Unmarshal(b, &param)
		if err == nil {
			c := &ConfigCli{
				ShutdownTime: fmt.Sprintf("%s %s", param.Date, param.Time),
				LunXunTime:   param.Zhouqi,
			}
			s := SetConfig(c, "conf.ini")
			if s == nil {
				//ServerCfg = NewConfig("conf.ini")
				ServerCfg.CliCfg = c
				fmt.Printf("%v\n", ServerCfg.CliCfg.LunXunTime)
				ctx.JSON(200, gin.H{"code": 0, "msg": "设置成功", "data": ""})
			} else {
				ctx.JSON(200, gin.H{"code": 1, "msg": "设置失败,保存配置文件失败", "data": ""})
			}
		} else {
			ctx.JSON(200, gin.H{"code": 1, "msg": "设置失败,参数错误", "data": err.Error()})
		}
	} else {
		ctx.JSON(200, gin.H{"code": 1, "msg": "设置失败", "data": err.Error()})
	}

}
